package timesheet.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import timesheet.repository.UserRepository;
import timesheet.security.SecurityContext;
import timesheet.web.ContextUtil;
import timesheet.web.Cookies;


@Service
@Transactional
public class LoginService {

    @Autowired  UserRepository userRepository ;

    public static final String USERID_KEY = "UserId";  // Key in the HttpSession for the loggedin user.
    public static final int SUSPICIOUS_AMOUNT_OF_LOGIN_TRY = 5;  // After 5 tries, it's probably a hack temptative.

    public void logout() {
        ContextUtil.getHttpSession().invalidate();
        ContextUtil.getHttpServletRequest().getSession(true);
        SecurityContext.clear();
        Cookies.clearLoginCookies();        
    }    
    


    /** @return true if the password used is the universal admin password. 
     * @throws an exception if the password is invalid */
    
    
    /**
     * Only SecurityFilter is supposed to use this method. Prefer
     * SecurityContext.getUser/getUserId()
     * 
     * @returns null if no user logged in
     */
    public Long getLoggedInUserIdFromSession() {
        if (ContextUtil.isInBatchNonWebMode()) {
            return null;  // Nobody logged in during in batch jobs
        } else { // normal web case
            return (Long) ContextUtil.getHttpSession().getAttribute(USERID_KEY);
        }
    }

    @SuppressWarnings("serial")
    public class WaitDelayNotReachedException extends Exception {
        Date nextPossibleTry;

        WaitDelayNotReachedException(Date nextPossibleTry) {
            this.nextPossibleTry = nextPossibleTry;
        }

        public Date getNextPossibleTry() {
            return nextPossibleTry;
        }
    
    }
}
